<?php
	function curlGetCookies($header,$cookie_array){
		preg_match_all("/Set-Cookie: (.*)/",$header,$arr);
		foreach($arr[1] as $cookie){
			preg_match("/^([^=]*)=([^;]*);/",$cookie,$ar);
			if(preg_match("/Domain=([^;]*);/",$cookie,$do)){$domain = $do[1];}else{$domain = "g";}
			if(preg_match("/Path=([^;]*);/",$cookie,$pa)){$path = $pa[1];}else{$path = "";}
			if($ar[2] == "EXPIRED" && isset($cookie_array[$ar[1]])){unset($cookie_array[$ar[1]]);continue;}

			//if(empty($cookie_array[$domain])){$cookie_array[$domain] = array();}
			$cookie_array[$ar[1]] = array("name"=>$ar[1],"value"=>$ar[2],"domain"=>$domain,"path"=>$path);
		}
		return $cookie_array;
	}
	function curlPutCookies($cookie_array){
		$masterCookie = "";
		if(!is_array($cookie_array)){return false;}
		foreach($cookie_array as $cookie){$masterCookie .= $cookie['name']."=".$cookie['value'].";";}
		return $masterCookie;
	}
	function curlSaveData($array,$file){
		$path = str_replace(basename($file),"",$file);
		if(!file_exists($path)){mkdir($path);}
		if(!is_writable($path)){return false;}
		$abre = fopen($file,"w");fwrite($abre,"<?\n\$serialized = '".urlencode(serialize($array))."';\n?>");fclose($abre);
	}
	function curlLoadData($file){include($file);return unserialize(urldecode($serialized));}

	function curlPetition($arr,$data){
		$curl = curl_init($arr['url']);
		if($GLOBALS['curl']['userAgent']){curl_setopt($curl,CURLOPT_USERAGENT,$GLOBALS['curl']['userAgent']);}
		if($arr['userAgent']){curl_setopt($curl,CURLOPT_USERAGENT,$arr['userAgent']);}
		if($arr['post']){curl_setopt($curl, CURLOPT_POST, true);curl_setopt($curl,CURLOPT_POSTFIELDS,$arr['post']);}
		if($arr['referer']){curl_setopt($curl,CURLOPT_REFERER,$arr['referer']);}
		if($arr['timeout']){curl_setopt($curl,CURLOPT_TIMEOUT,$arr['timeout']);}
		curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,FALSE);
		curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,2);
		curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
		curl_setopt($curl,CURLOPT_HEADER, true);

		$cookieSrc = "cookie.txt";if($GLOBALS['curl']['cookieFile']){$cookieSrc = $GLOBALS['curl']['cookieFile'];}
		curl_setopt($curl,CURLOPT_COOKIEFILE,$cookieSrc);
		curl_setopt($curl,CURLOPT_COOKIEJAR,$cookieSrc);
		if($arr['header']){curl_setopt($curl,CURLOPT_HTTPHEADER,$arr['header']);}
		curl_setopt($curl,CURLOPT_TIMEOUT,25);
		
		$viewcode = curl_exec($curl);
		curl_close($curl);

		$data['cookie_array'] = curlGetCookies($viewcode,$data['cookie_array']);
		$data['viewcode'] = $viewcode;

		if(preg_match("/HTTP\/1\.1 302/",$viewcode)){
			preg_match("/Location: (.*)/",$viewcode,$p);
			$nurl = trim($p[1]);
			if($nurl[0]=="/"){list($arr['url'],) = explode("/",str_replace("http://","",$arr['url']));$nurl = "http://".$arr['url'].$nurl;}
			$arr['url'] = $nurl;
			if($arr['followLocation'] || $arr['followlocation']){unset($arr['post']);return curlPetition($arr,$data);}
		}

		return $data;
	}
?>
